<template>
    <el-form :inline="false" :model="formInline" class="demo-form-inline" label-width="auto">
        <el-form-item label="项目">
            <el-select v-model="form.itemId" placeholder="请选择项目" style="width: 220px">
                <el-option v-for="item in nursingNames" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="购买数量">
            <el-input v-model="form.nurseNumber" />
        </el-form-item>
        <!-- <el-form-item label="等级">
            <el-select v-model="form.levelId" placeholder="请选择项目" style="width: 220px">
                <el-option v-for="item in nursingLevelNames" :key="item.value" :label="item.label"
                    :value="item.value" />
            </el-select>
        </el-form-item> -->
        <div class="block">
            <span class="demonstration">服务购买日期</span>
            <el-date-picker v-model="form.buyTime" type="datetime" placeholder="Select date and time" />
        </div>
        <div class="block">
            <span class="demonstration">服务到期日期</span>
            <el-date-picker v-model="form.maturityTime" type="datetime" placeholder="Select date and time" />
        </div>
        <el-form-item class="bottoms">
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="cancelSetAdd">取消</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup name="setadd">
import { ref, reactive } from "vue";
import { listItem, listLevel } from '@/api/CareManagement/careLevel/index';
import { addSet, getById } from '@/api/CareManagement/careSetup/index';
import { ElMessageBox, ElNotification } from "element-plus";
import { onMounted } from "vue";

const props = defineProps({
    closeSetAdd: {
        type: Function,
        required: true
    },
    customerId: {
        type: Number,
        required: true
    },
    levelIdold: {
        type: Number,
        required: true
    },
    setId: {
        type: Number,
        required: true
    }
});
console.log("setadd", props);

const buytime = ref(new Date())
const maturitytime = ref(new Date())
const form = reactive({
    itemId: null,
    customerId: props.customerId,
    levelId: props.levelIdold,
    nurseNumber: "",
    buyTime: "",
    maturityTime: "",
});

const nursingNames = ref([]);
const nursingLevelNames = ref([]);
const cancelSetAdd = (refresh = false) => {
    props.closeSetAdd(refresh);
};
const formatDate = (date) => {
    if (!date) return "";
    // 确保输入值为 Date 对象
    if (!(date instanceof Date)) {
        date = new Date(date); // 尝试将字符串转换为 Date 对象
    }
    if (isNaN(date.getTime())) {
        console.error("Invalid date:", date);
        return ""; // 如果日期无效，返回空字符串
    }
    const padZero = (num) => String(num).padStart(2, "0");
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1);
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());
    const seconds = padZero(date.getSeconds());
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const onSubmit = () => {
    console.log("form", form);
    // 格式化日期
    form.buyTime = formatDate(form.buyTime);
    form.maturityTime = formatDate(form.maturityTime);

    console.log("upup", form);
    addSet(form).then((success) => {
        ElNotification({
            title: "消息",
            type: "success",
            message: "保存成功",
        });
        cancelSetAdd(true); // 确保传递 true 以触发父组件刷新
    });
};
const pageGetById = async () => {
    try {
        const data = await getById(props.setId);
        if (data) {
            Object.assign(form, data); // 将 data 的属性逐一赋值给 form
            console.log("form", form);
        }
    } catch (error) {
        console.error("获取护理信息失败:", error);
    }
};
onMounted(async () => {
    try {
        if (props.setId) {
            pageGetById();
        }
        const data = await listItem();
        const data2 = await listLevel();
        if (Array.isArray(data)) {
            nursingNames.value = data.map(item => ({
                value: item.id,
                label: item.nursingName
            }));
            nursingLevelNames.value = data2.map(item => ({
                value: item.id,
                label: item.levelName
            }));
        } else {
            console.error("获取到的数据不是一个数组:", data);
            nursingNames.value = [];
        }
    } catch (error) {
        console.error("获取护理信息失败:", error);
    }
});
</script>
<style scoped>
.demo-form-inline {

    padding: 15px 5px;
}

.block {
    margin-top: 22px;
    /* 保留：为日期选择器添加外边距 */
}

.el-form-item {
    margin-bottom: 22px;
    /* 新增：增加表单项之间的垂直间距 */
}

.bottoms {
    /* 新增：使用弹性布局 */
    justify-content: flex-end;
    /* 新增：内容靠右对齐 */
    margin-top: 22px;
}
</style>